package com.wpzf.zxhc.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wpzf.common.core.text.Convert;
import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.system.api.domain.SysUser;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.utils.ExcelUtils;
import com.wpzf.zxhc.domain.*;
import com.wpzf.zxhc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jltask")
public class WpzfJlHcTaskController {

    @Autowired
    WpzfJlHcTaskService wpzfJlHcTaskService;

    @Autowired
    TokenService tokenService;

    @Autowired
    CommonService commonService;

    @Autowired
    WpzfShTbService wpzfShTbService;

    @Value("${tempath}")
    public String tempath;

    /*获取未完成任务列表*/
    @Log(title = "获取未完成任务列表", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/query_jl_w_task", method = RequestMethod.POST)
    public AjaxResult query_jl_w_task(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        parm.put("dwmc", loginUser.getSysUser().getDept().getDeptName());
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_w_task(parm);
        Integer cnt = wpzfJlHcTaskService.query_jl_w_task_count(parm);
        if (rest != null) {
            return AjaxResult.success("获取未完成任务列表成功", rest, cnt);
        }

        return AjaxResult.error("获取未完成任务列表失败", -1);
    }

    /*获取当前用户所有未完成任务（左侧列表）*/
    @RequestMapping(value = "/query_jl_w_left_task_list", method = RequestMethod.POST)
    public AjaxResult query_jl_w_left_task_list(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        parm.put("dwmc", loginUser.getSysUser().getDept().getDeptName());

        //获取当前用户所有未完成任务
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_w_left_task_list(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有未完成任务（左侧列表）成功", rest);
        }

        return AjaxResult.error("获取当前用户所有未完成任务（左侧列表）失败", -1);
    }

    //获取当前用户未完成任务所有省份
    @RequestMapping(value = "/query_jl_wwc_Provs", method = RequestMethod.POST)
    public AjaxResult query_jl_wwc_Provs(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        //获取当前用户所有已完成的任务
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_wwc_Provs(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前未完成任务用户所有省份表成功", rest);
        }
        return AjaxResult.error("获取当前用户未完成任务所有省份失败", -1);
    }

    //获取当前用户未完成任务所有区县
    @RequestMapping(value = "/query_jl_wwc_Citys", method = RequestMethod.POST)
    public AjaxResult query_jl_wwc_Citys(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_wwc_Citys(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户未完成任务所有区县成功", rest);
        }

        return AjaxResult.error("获取当前用户未完成任务所有区县失败", -1);
    }

    /*获取当前用户所有已完成任务*/
    @RequestMapping(value = "/query_jl_y_task", method = RequestMethod.POST)
    public AjaxResult query_jl_y_task(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        parm.put("dwmc", loginUser.getSysUser().getDept().getDeptName());
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_y_task(parm);
        Integer cnt = wpzfJlHcTaskService.query_jl_y_task_count(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有已完成任务列表成功", rest, cnt);
        }
        return AjaxResult.error("获取当前用户所有已完成任务列表失败", -1);
    }

    /*获取当前用户所有已完成任务（左侧列表）*/
    @RequestMapping(value = "/query_jl_y_left_task_list", method = RequestMethod.POST)
    public AjaxResult query_jl_y_left_task_list(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        parm.put("dwmc", loginUser.getSysUser().getDept().getDeptName());

        //获取当前用户所有未完成任务
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_y_left_task_list(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有已完成任务（左侧列表）成功", rest);
        }
        return AjaxResult.error("获取当前用户所有已完成任务（左侧列表）失败", -1);
    }

    //获取当前用户所有已完成任务的省份
    @RequestMapping(value = "/query_jl_ywc_Provs", method = RequestMethod.POST)
    public AjaxResult query_jl_ywc_Provs(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        //获取当前用户所有已完成的任务
        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_ywc_Provs(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有已完成任务的省份成功", rest);
        }

        return AjaxResult.error("获取当前用户所有已完成任务的省份失败", -1);
    }

    //获取当前用户所有已完成任务的区县
    @RequestMapping(value = "/query_jl_ywc_Citys", method = RequestMethod.POST)
    public AjaxResult query_jl_ywc_Citys(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_ywc_Citys(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有已完成任务的区县成功", rest);
        }

        return AjaxResult.error("获取当前用户所有已完成任务的区县失败", -1);
    }



  /*//用户提交图斑
  @RequestMapping(value = "/updateSubmitList", method = RequestMethod.POST)
  public AjaxResult updateSubmitList(@RequestBody Map<String, Object> parm) {
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

    parm.put("ywhj","1");
    parm.put("username", loginUser.getUsername());
    String tbbhs = parm.get("tbbhs") + "";
    int rest = 0;
    if (tbbhs != null && !tbbhs.equals("") && !tbbhs.equals("null") && !tbbhs.equals("|")) {

      String[] list = tbbhs.split("\\|");
      if (list.length > 0) {
        for (int i = 0; i < list.length; i++) {
          String tbbh = list[i];

          ModelMap item = new ModelMap();
          item.put("tbbh", tbbh);
          item.put("pch", parm.get("pch")+"");
          item.put("sftj", "是");
          item.put("sftj_submitdate", new SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(new Date()));
          item.put("xzqdm", parm.get("xzqdm")+"");
          item.put("username", loginUser.getUsername());

          //添加监理任务
          if(wpzfJlHcTaskService.updateSubmit(item)>0) {

            wpzfJlHcTaskService.updateJlSubmit(item);
            Map<String, Object> tbbhModel = wpzfShTbService.querybytbbh(parm);
            if (tbbhModel != null) {
              wpzfShTbService.deleteTb(parm);
            }
            ModelMap model = new ModelMap();
            model.put("tbbh", tbbh);
            model.put("username", loginUser.getUsername());
            model.put("realname", loginUser.getSysUser().getNickName());
            model.put("dwmc", loginUser.getSysUser().getDept().getDeptName());
            model.put("pch", parm.get("pch"));
            model.put("xzqdm", parm.get("xzqdm"));
            model.put("ywhj", parm.get("ywhj"));
            wpzfShTbService.addShTb(model);

            rest++;
          }
        }
      }
    }

    if (rest > 0) {
      return AjaxResult.success("批量提交成功，成功提交******" + rest + "个******图斑");
    }
    return AjaxResult.error("批量提交失败", -1);
  }*/

    //监理提交图斑
    @RequestMapping(value = "/updateSubmitList", method = RequestMethod.POST)
    public AjaxResult updateSubmitList(@RequestBody Map<String, Object> parms) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parms.put("username", loginUser.getUsername());
        parms.put("realname", loginUser.getSysUser().getNickName());
        parms.put("dwmc", loginUser.getSysUser().getDept().getDeptName());

        Integer rest = wpzfJlHcTaskService.updateSubmitList(parms);
        if (rest > 0) {
            return AjaxResult.success("批量提交成功，成功提交******" + rest + "个******图斑");
        }
        return AjaxResult.error("批量提交失败", -1);
    }

    //监理负责人分配图斑
    @RequestMapping(value = "/updateTbbh", method = RequestMethod.POST)
    public AjaxResult updateTbbh(@RequestBody Map<String, Object> parm) {
        Integer rest = wpzfJlHcTaskService.updateTbbh(parm);
        if (rest > 0) {
            return AjaxResult.success("监理负责人分配图斑，成功");
        }
        return AjaxResult.error("监理负责人分配图斑 失败", -1);
    }

  /*public AjaxResult updateTbbh(@RequestBody Map<String, Object> parm) {
    int rest = 0;
    String tbList= parm.get("tblist")+"";
    String[] list=tbList.split("\\|");;
    if(list.length>0) {

      String userList = parm.get("userlist") + "";
      String[] users = userList.split("\\|");
      if (users.length > 0) {

        Integer remainderCount = (list.length) % (users.length);
        //每个人分配数
        Integer divideCount = list.length / users.length;
        Integer aVGCount = divideCount;
        System.out.println("总数:" + list.length + " 人数:" + users.length + " 余数:" + remainderCount + " 除数:" + divideCount);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < users.length; i++) {
          String user=users[i]+"";
          String[] u_model=user.split("-");
          Integer startCount = 0;
          if (i == 0) {
            startCount = 0;
          } else if (i == (users.length - 1)) {
            startCount = divideCount;
            divideCount = list.length;
          } else {
            startCount = (divideCount);
            divideCount = divideCount + aVGCount;
          }
          for (int j = startCount; j < divideCount; j++) {
            sb.setLength(0);

            ModelMap item = new ModelMap();
            item.put("tbbh", list[j]);
            item.put("pch", parm.get("pch") + "");
            item.put("realname",u_model[1]);
            item.put("jl_fpdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            item.put("xzqdm", parm.get("xzqdm") + "");
            item.put("username", u_model[0]);
            if (wpzfJlHcTaskService.updateTbbh(item) > 0) {
              rest++;
            }
          }
        }
      }
    }

    if (rest > 0) {
      return AjaxResult.success("图斑分配成功！",rest);
    }
    return AjaxResult.error("图斑分配失败", -1);
  }*/


    //获取所有批次号（列表）************  监理负责人
    @RequestMapping(value = "/get_jl_pchlist", method = RequestMethod.POST)
    public AjaxResult get_jl_pchlist(@RequestBody Map<String, Object> parm) {
        List<Map<String, Object>> rest = wpzfJlHcTaskService.get_jl_pchlist(parm);
        //  int cnt=wpzfJlHcTaskService.query_jl_tasklist_count(parm);
        if (rest != null) {
            return AjaxResult.success("获取所有批次号成功", rest);
        }

        return AjaxResult.error("获取所有批次号失败", -1);
    }

    //获取所有的未分配图斑（列表）************  监理负责人
    @RequestMapping(value = "/query_not_fptb_count", method = RequestMethod.POST)
    public AjaxResult query_not_fptb(@RequestBody Map<String, Object> parm) {
        int rest = wpzfJlHcTaskService.query_not_fptb_count(parm);
        if (rest > 0) {
            return AjaxResult.success("获取所有的未分配图斑成功", rest);
        }
        return AjaxResult.success("", 0);
    }

    @RequestMapping(value = "/query_kc_count", method = RequestMethod.POST)
    public AjaxResult query_kc_count(@RequestBody Map<String, Object> parm) {
        int rest = wpzfJlHcTaskService.query_kc_count(parm);
        if (rest > 0) {
            return AjaxResult.success("获取所有的扣除图斑数量成功", rest);
        }
        return AjaxResult.success("", 0);
    }

    //获取所有监理（列表）************  监理负责人
    @RequestMapping(value = "/get_jl_userlist", method = RequestMethod.POST)
    public AjaxResult get_jl_userlist(@RequestBody Map<String, Object> parm) {
        List<Map<String, Object>> rest = wpzfJlHcTaskService.get_jl_userlist(parm);
        if (rest != null) {
            return AjaxResult.success("获取所有监理成功", rest);
        }
        return AjaxResult.error("获取所有监理失败", -1);
    }

    //获取当前所有任务（列表）************  监理负责人
    @RequestMapping(value = "/query_jl_tasklist", method = RequestMethod.POST)
    public AjaxResult query_jl_tasklist(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_tasklist(parm);
        Integer cnt = wpzfJlHcTaskService.query_jl_tasklist_count(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前所有任务成功", rest, cnt);
        }
        return AjaxResult.error("获取当前所有任务失败", -1);
    }

    //获取当前所有任务（左侧列表）************  监理负责人
    @RequestMapping(value = "/query_jl_task_Leftlist", method = RequestMethod.POST)
    public AjaxResult query_jl_task_Leftlist(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_task_Leftlist(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前所有任务成功", rest);
        }
        return AjaxResult.error("获取当前所有任务失败", -1);
    }

    /*获取当前用户所有任务的省份*/
    @RequestMapping(value = "/query_jl_Provs", method = RequestMethod.POST)
    public AjaxResult query_jl_Provs(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_Provs(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有任务的省份列表成功", rest);
        }
        return AjaxResult.error("获取当前用户所有任务的省份失败", -1);
    }

    /*获取当前用户所有任务的区县*/
    @RequestMapping(value = "/query_jl_Citys", method = RequestMethod.POST)
    public AjaxResult query_jl_Citys(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_Citys(parm);
        if (rest != null) {
            return AjaxResult.success("获取当前用户所有任务的区县列表成功", rest);
        }

        return AjaxResult.error("获取当前用户所有任务的区县失败", -1);
    }

    //根据区县统计监理完成情况（列表）************  监理负责人
    @RequestMapping(value = "/query_jl_static", method = RequestMethod.POST)
    public AjaxResult query_jl_static(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        List<Map<String, Object>> rest = wpzfJlHcTaskService.query_jl_static(parm);
        int cnt = wpzfJlHcTaskService.query_jl_static_count(parm);
        if (rest != null) {
            return AjaxResult.success("根据区县统计监理完成情况成功", rest, cnt);
        }

        return AjaxResult.error("根据区县统计监理完成情况失败", -1);
    }

    //查询当前图斑是否核查（列表）************  监理负责人
    @RequestMapping(value = "/query_jl_user_hcjg", method = RequestMethod.POST)
    public AjaxResult query_jl_user_hcjg(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());

        int cnt = wpzfJlHcTaskService.query_jl_user_hcjg(parm);
        if (cnt > 0) {
            return AjaxResult.success("查询当前图斑是否核查成功", cnt);
        }

        return AjaxResult.error("查询当前图斑是否核查失败", -1);
    }

    /*获取上一个图斑*/
    @RequestMapping(value = "/get_last_next_tbbh", method = RequestMethod.POST)
    public AjaxResult get_last_next_tbbh(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        String ywhj = parm.get("ywhj") + "";
        String state = parm.get("state") + "";
        List<Map<String, Object>> list = new ArrayList<>();
        String selectList = parm.get("listParams").toString();
        if (!selectList.equals("") && !selectList.equals("null") && selectList != null) {
            ModelMap model = new ModelMap();

            JSONObject obj = JSON.parseObject(selectList);
            if (obj != null) {
                model.put("username", loginUser.getUsername());
                model.put("dwmc", loginUser.getSysUser().getDept().getDeptName());
                model.put("xzqdm", obj.getString("xzqdm"));
                model.put("pch", parm.get("pch") + "");
                model.put("sfcf", obj.getString("sfcf"));
                model.put("pdlx", obj.getString("pdlx"));
                model.put("hczt", obj.getString("hczt"));
                model.put("ids", parm.get("ids"));

                if (ywhj.equals("0") && state.equals("未完成")) {
                    list = wpzfJlHcTaskService.query_jl_w_task_list(model);
                } else if (ywhj.equals("0") && state.equals("已完成")) {
                    list = wpzfJlHcTaskService.query_jl_y_task_list(model);
                } else if (ywhj.equals("1") && state.equals("未完成")) {
                    list = wpzfJlHcTaskService.query_jl_y_task_list(parm);
                } else if (ywhj.equals("1") && state.equals("已完成")) {
                    list = wpzfJlHcTaskService.query_jl_y_task_list(parm);
                } else if (ywhj.equals("2") && state.equals("待确认")) {
                    // list = wpzfJlHcTaskService.get_unit_dqr_static_list(model);
                } else if (ywhj.equals("2") && state.equals("已确认")) {
                    // list = wpzfJlHcTaskService.get_unit_yqr_static_list(model);
                }
            }
        }
        return AjaxResult.success("获取上一个图斑", list);
    }

    //导出
    @RequestMapping(value = "/export", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AjaxResult export(@RequestBody Map<String, Object> parm, HttpServletResponse response) {
        ExcelUtils excel = new ExcelUtils();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String msg = "";
        String rest = "";
        String category = parm.get("category") + "";
        String xzqdm = "130125";
        List<String> Colomnlist = new ArrayList<>();
        try {
            parm.put("username", loginUser.getUsername());

            System.out.println(tempath);
            if (category.equals("任务情况统计（用户）")) {
                Colomnlist.clear();
                Colomnlist.add("序号");
                Colomnlist.add("所属省");
                Colomnlist.add("所属区县");
                Colomnlist.add("区县代码");
                Colomnlist.add("批次号");
                Colomnlist.add("图斑总数");
                Colomnlist.add("提交状态");
                Colomnlist.add("已核查图斑数量");
                Colomnlist.add("待确认图斑数量");
                Colomnlist.add("已确认图斑数量");
                List<Map<String, Object>> list = wpzfJlHcTaskService.query_jl_static(parm);
                rest = excel.export(response, category, list, Colomnlist, tempath);
            } else if (category.equals("监理核查进度情况")) {
                parm.put("dwmc", loginUser.getSysUser().getDept().getDeptName());
                Colomnlist.clear();
                Colomnlist.add("序号");
                Colomnlist.add("用户名");
                Colomnlist.add("监理姓名");
                Colomnlist.add("图斑任务总数");
                Colomnlist.add("已提交图斑数量");
                Colomnlist.add("未提交图斑数量");
                Colomnlist.add("整改图斑数量");
                List<Map<String, Object>> list = wpzfJlHcTaskService.query_jl_static(parm);
                rest = excel.export(response, category, list, Colomnlist, tempath);
            }
            if (rest.contains("error")) {
                msg = "导出失败";
            } else {
                msg = "导出成功";
            }
            return AjaxResult.success(msg, rest);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "导出失败";
        }
        return AjaxResult.error(msg, -1);
    }


    //监理核查任务统计
    @Log(title = "监理核查任务统计", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/getUserTaskStatistics", method = RequestMethod.POST)
    public AjaxResult getUserTaskStatistics(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        List<Map<String, Object>> rest = wpzfJlHcTaskService.getUserTaskStatistics(parm);
        Integer cnt = wpzfJlHcTaskService.getUserTaskStatisticsCount(parm);
        if (rest != null) {
            return AjaxResult.success("监理核查任务统计 成功", rest, cnt);
        }
        return AjaxResult.error("监理核查任务统计", -1);
    }

}
